<template>
  <div class="app-container">
    <div v-if="!isEdit">
      <el-row>
        <el-card class="box-card" el-card__headerbg>
          <div slot="header" class="clearfix">
            <span>订单详情</span>
          </div>

          <!-- 可以使用span 和 span-map对象来控制栅格的大小 -->
          <el-description >
            <el-description-item label="订单编号" :value="order.orderNo" :span="6"/>

            <!--  ////订单状态 0 - 未支付   1 - 支付中  2 - 已支付  3 - 已评价  4 - 订单取消
  //                    *         5 -   6 - 发起退货  7 - 同意退货  8 - 退货完成  9 - 拒绝退货
  //                    *         10 - 确认订单（已发货）  11 - 已收货-->
            <!--        <el-description-item label="订单状态" :value="order.status" :span="6" />-->
            <el-description-item label="订单状态" v-if="order.status === 0" :span="6" value="未支付"/>
            <el-description-item label="订单状态" v-if="order.status === 1" :span="6" value="支付中"/>
            <el-description-item label="订单状态" v-if="order.status === 2" :span="6" value="已支付"/>
            <el-description-item label="订单状态" v-if="order.status === 3" :span="6" value="已核销"/>
            <el-description-item label="订单状态" v-if="order.status === 4" :span="6" value="订单取消"/>
            <el-description-item label="订单状态" v-if="order.status === 5" :span="6" value="已评价"/>
            <el-description-item label="订单状态" v-if="order.status === 6" :span="6" value="发起退货"/>
            <el-description-item label="订单状态" v-if="order.status === 7" :span="6" value="同意退货"/>
            <el-description-item label="订单状态" v-if="order.status === 8" :span="6" value="退货完成"/>
            <el-description-item label="订单状态" v-if="order.status === 9" :span="6" value="拒绝退货"/>
            <el-description-item label="订单状态" v-if="order.status === 10" :span="6" value="确认订单"/>
            <el-description-item label="订单状态" v-if="order.status === 11" :span="6" value="已收货"/>


            <el-description-item label="总订单金额" :value="order.totalPrice+'元'" :span="6"/>
            <el-description-item label="需支付" :value="order.payPrice+'元'" :span="6"/>
            <el-description-item label="下单时间" :value="order.createTime" :span="6"/>
            <el-description-item label="支付时间" :value="order.payTime" :span="6"/>
            <el-description-item label="用户姓名" :value="order.realName" :span="6"/>
            <el-description-item label="用户手机号" :value="order.userPhone" :span="6"/>
          </el-description>
        </el-card>
      </el-row>

      <el-row :gutter="10" class="mb8" style="margin-top: 20px;">

        <el-col :span="1.5">
          <router-link :to="'/mer/table?merId=' + merId" class="link-type">
            <el-button icon="el-icon-back" size="mini">
              返 回
            </el-button>
          </router-link>
        </el-col>
      </el-row>

      <el-table v-loading="loading" :data="orderInfoList" style="margin-top: 20px;"  @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="商品名称" align="center" prop="productName"/>
        <el-table-column label="商品规格" align="center" prop="skuName" />
        <el-table-column label="商品单价" align="center" prop="singlePrice" >
          <template slot-scope="scope">{{scope.row.singlePrice}}元</template>
        </el-table-column>
        <el-table-column label="购买数量" align="center" prop="count">
          <template slot-scope="scope">
            {{scope.row.count}} 份
<!--&lt;!&ndash;            (currentValue, oldValue) => numChange(currentValue, oldValue, row)&ndash;&gt;-->
<!--            <el-input-number v-model="scope.row.count" @change="(currentValue, oldValue) => handleCountChange(currentValue, oldValue, scope.row)" :min="1" />-->
          </template>
        </el-table-column>
        <el-table-column label="订单总价" align="center" prop="totalMoney" >
          <template slot-scope="scope">{{scope.row.totalMoney}}元</template>
        </el-table-column>
        <el-table-column label="操作" align="center" prop="status">
          <template slot-scope="scope">
            <div>
              <!-- 订单状态 0 - 未支付   1 - 待支付  2 - 已支付  3 - 已核销 4 - 已评价
              5 - 订单取消  6 - 已申请退货  7 - 同意退货  8 - 退货完成 9 - 拒绝退货 10 - 已完成 -->
<!--              <el-tag style="cursor: pointer" :type="''" v-if="order.status == 0 || order.status == 1" @click="handleUpdate(scope.row)">编辑</el-tag>-->


              <el-tag v-if="scope.row.isMerCheck === 0" style="cursor: pointer" :type="'info'">未核销</el-tag>
              <!--<el-tag v-if="scope.row.isMerCheck === 1" style="cursor: pointer" :type="''">已核销</el-tag>-->
              <el-tag v-if="scope.row.isMerCheck === 2" style="cursor: pointer" :type="''">已核销</el-tag>
<!--              <el-tag v-if="(order.status === 0 || order.status === 1) && scope.row.isDel == 0"-->
<!--                      style="cursor: pointer" :type="'danger'" @click="handleDelete(scope.row)">删除</el-tag>-->
              <el-button size="mini" type="text" v-if="(order.status === 0 || order.status === 1) && scope.row.isDel == 0" icon="el-icon-delete" @click="handleDelete(scope.row)"
                         v-hasPermi="['module:product:remove']">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div style="margin: 40px; font-size: 40px;">
        <label>总计：{{order.payPrice}} 元</label>
      </div>
    </div>

    <el-dialog :title="title" :visible.sync="open1" width="550px" append-to-body>
      <el-form ref="form" :model="order" :rules="rules" label-width="110px">
        <el-form-item label="订单总价" prop="totalPrice">
          <el-input v-model="order.totalPrice" placeholder="请输入订单总价" size="mini" @input="inputTotalPrice">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="商家折扣" prop="discountRate">
          <el-input v-model="order.discountRate" readonly placeholder="请输入商家折扣" size="mini">
            <template slot="append">折</template>
          </el-input>
        </el-form-item>
        <el-form-item label="支付金额" prop="payPrice">
          <el-input v-model="order.payPrice" readonly placeholder="请输入支付金额" size="mini">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="会员余额"  v-if="selfVip!=0" prop="accountMoney">
          <el-input v-model="selfVip.accountMoney" readonly placeholder="请输入支付金额" size="mini">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" size="mini" type="success" v-if="selfVip!=0" @click="submitVipJiesuan">会员余额结算</el-button>
        <el-button :loading="buttonLoading" size="mini" type="primary" @click="submitJiesuan">线下扫码结算</el-button>
        <el-button @click="canceljiesuan" size="mini">取 消</el-button>
      </div>
    </el-dialog>

    <div v-if="isEdit">
      <el-button icon="el-icon-back" size="mini" @click="cancelEdit">
        返 回
      </el-button>
      <div style="margin-left:10%;width: 70%;">
        <el-form ref="form" :model="formInfo" :rules="rules" label-width="100px" class="product-edit-view ">
          <el-row>
            <!--左部分-->
            <el-col :span="12">
              <el-row>
                <el-col :span="24">
                  <el-form-item label="商品分类" prop="cateId" style="width:100%;">
                    <el-select v-model="formInfo.cateId" style="width: 100%;" @change="changeProductType" clearable size="mini">
                      <el-option v-for="item in productTypeOptions"
                                 :key="item.id" :label="item.typeName"
                                 :value="parseInt(item.id+'')">{{ item.typeName }}
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-form-item label="商品" prop="productId" >
                  <el-col :span="8" v-for="product in productList" style="padding: 10px;">
                    <el-card :body-style="{ padding: '5px',}">
                      <img :src="product.imagePath" class="image" style="height:100px;">
                      <div style="line-height: 25px;">
                        <el-row class="card-view-text">
                          <span style="font-size: 12px;">{{product.storeName}}</span>
                        </el-row>
                        <div class="bottom clearfix">
                          <el-button type="text" class="button" size="mini" @click="chooseProduct(product)">选择</el-button>
                        </div>
                      </div>
                    </el-card>
                  </el-col>
                </el-form-item>
              </el-row>

              <el-row >
                <el-form-item >
                  <pagination v-show="totalGoods > 0"
                              :total="totalGoods"
                              :page.sync="queryParamsProduct.pageNum"
                              :limit.sync="queryParamsProduct.pageSize"
                              @pagination="getGoodsList" />
                </el-form-item>
              </el-row>

            </el-col>

            <!--右部分-->
            <el-col :span="12">
              <el-row>
                <el-col :span="24">
                  <el-form-item label="商品规格" prop="skuId">
                    <el-select v-model="formInfo.skuId" style="width: 100%;" clearable size="mini" placeholder="请选择规格">
                      <el-option v-for="item in attrValues"
                                 :key="item.id" :label="item.sku+ ' ' + item.price +'元'"
                                 :value="parseInt(item.id+'')">{{ item.sku + ' ' + item.price +'元'}}
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="24">
                  <el-form-item label="数量" prop="count">
                    <el-input v-model="formInfo.count" placeholder="请输入购买数量" size="mini" type="number"/>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <div style="text-align: center">
                    <el-button :loading="buttonLoading" type="primary" size="mini" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel" size="mini">取 消</el-button>
                  </div>
                </el-col>
              </el-row>
            </el-col>

          </el-row>
        </el-form>

      </div>
    </div>

  </div>
</template>

<script>
  import {listProduct, } from "@/api/module/product/list";
  import { listInfo, getInfo,updateInfo,addInfo,delInfo,printInfo  } from "@/api/module/product/orderinfo";
  import {listType, listAll} from "@/api/module/product/type";

  import {listAttrValue} from "@/api/module/product/attrValue";
  // 引入组件
  import ElDescription from '@/components/Description'
  import ElDescriptionItem from '@/components/Description/item'
  import {
    getMerOrder,
    printOrder0,
    printOrder1,
    printOrder2, printOrderCounter,
    updateOrder,
    updateVipOrder
  } from "@/api/module/product/order";

  export default {
    name: "Order",
    components:{
      ElDescription, ElDescriptionItem
    },
    data() {
      return {
        dialogVisible:false,
        orderIds:undefined,
        // 按钮loading
        buttonLoading: false,
        // 遮罩层
        loading: true,
        // 导出遮罩层
        exportLoading: false,
        // 选中数组
        ids: [],
        //总类
        productTypeOptions: [],
        //子分类
        productTypeChildOptions: [],
        productList:[],
        isEdit:false,
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        dateRange:[],
        // 总条数
        total: 0,
        totalGoods:0,
        // 订单表格数据
        orderInfoList: [],
        // 弹出层标题
        title: "",
        // 弹出层标题
        titleTable: "",
        // 是否显示弹出层
        open: false,
        openTable: false,
        merId:0,
        open1:false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 1000,
          orderId:undefined,
          status:undefined,
          orderNo: undefined,
          beginDate:undefined,
          endDate:undefined,
        },
        // 查询参数
        queryParamsPty: {
          pageNum: 1,
          pageSize: 100,
          merId:undefined,
        },
        // 查询参数
        queryParamsProduct: {
          pageNum: 1,
          pageSize: 8,
          cateId: undefined,
          cateChildId: undefined,
        },
        // 查询参数
        queryParamsAttrValue: {
          productId: undefined,
          pageNum: 1,
          pageSize: 100,
          isDel:0,
        },
        attrValues:[],
        tableList:[],
        orderId:0,
        from:{},
        order:{},
        formInfo:{

        },
        nowTable:{},
        selfVip:{},
        payList:{},
        // 表单参数
        form: {},
        // 表单校验
        rules: {
        }
      };
    },
    created() {
      console.log('orderinfo  this.$route.query',this.$route.query);
      this.orderId = this.$route.query.orderId ? this.$route.query.orderId : 0;
      this.queryParams.orderId = this.$route.query.orderId ? this.$route.query.orderId : 0;
      this.merId = this.$route.query.merId ? this.$route.query.merId : 0;
      this.from =  this.$route.query.from ? this.$route.query.from : 'order';
      this.queryParamsPty.merId = this.$route.query.merId ? this.$route.query.merId : 0;
      this.getList();
    },
    methods: {
      /** 查询商品列表 */
      getGoodsList() {
        this.productList = [];
        // this.totalGoods = 0;
        listProduct(this.queryParamsProduct).then(response => {
          console.log('getGoodsList',response.rows);
          this.productList = response.rows;
          this.totalGoods = response.total;
        });
      },
      inputTotalPrice(val){
        console.log("inputTotalPrice",val);
        var total = val;
        var rate = this.order.discountRate;
        var payMoney = val * rate / 10;
        this.order.payPrice = payMoney;
      },
      handleJieSuan(){
        this.open1 = true;
        if (this.$route.query.orderId!=undefined){
          const id = this.$route.query.orderId;
          getMerOrder(id).then(response => {
            this.loading = false;
            this.payList = response;
            this.open = true;
            this.title = "修改订单";
            console.log(this.payList)
          });
        }
      },
      handleChangeTable(){
        this.openTable = true;
      },
      canceljiesuan(){
        this.open1=false
      },
      submitJiesuan(){
        this.open1 = false;
        this.order.status = 2;
        // const id = this.$route.query.orderId;
        updateOrder(this.order).then(response => {
          if(response.code == 200){
            this.msgSuccess("结账成功");
            this.getList();
          }else{
            this.msgError("结账失败");
          }
        });
        console.log(this.order)
      },
      submitChangeTable(){
        this.open1 = false;
        updateOrder(this.order).then(response => {
          if(response.code == 200){
            this.msgSuccess("更改成功");
            this.openTable = false;
            this.getList();
          }else{
            this.msgError("更改失败");
          }
        });
        console.log(this.order)
      },
      submitVipJiesuan(){
        this.open1 = false;
        this.order.status = 2;
        this.order.selfVipId==this.selfVipId;
        // const id = this.$route.query.orderId;
        updateVipOrder(this.order).then(response => {
          if(response.code == 200){
            this.msgSuccess("结账成功");
            this.getList();
          }else{
            this.msgError("结账失败");
          }
        });
      },
      getProductValue(){
        listAttrValue(this.queryParamsAttrValue).then(response => {
          this.attrValues = response.rows;
          if(this.attrValues!=undefined){
            this.formInfo.skuId = response.rows[0].id;
            this.formInfo.singlePrice = response.rows[0].price;
            this.formInfo.count = 1;
          }
        });
      },
      chooseProduct(product){
        console.log('chooseProduct', product);
        this.queryParamsAttrValue.productId = product.id;
        this.formInfo.productId = product.id;
        this.formInfo.isVerify = 0;
        this.formInfo.verifyCount = 0;
        this.formInfo.state = 1;
        this.formInfo.isFc = 0;
        this.formInfo.merRate = 0;
        this.formInfo.merFee = 0;
        this.formInfo.merSettlement = 0;
        this.getProductValue();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id);
        this.single = selection.length!==1;
        this.multiple = !selection.length;
      },
      /** 查询订单列表 */
      getList() {
        this.loading = true;
        listInfo(this.queryParams).then(response => {
          console.log(response)
          this.orderInfoList = response.rows;
          this.total = response.total;
          this.loading = false;
          this.order = response.otherData.order;
          this.tableList = response.otherData.merTables;
          this.nowTable = response.otherData.table;
          if (response.otherData.selfVip!=undefined){
            this.selfVip = response.otherData.selfVip;
          }else {
            this.selfVip=0;
          }
        });
      },
      getProductList(isChild,cateId) {
        if(isChild == 0){
          this.queryParamsProduct.cateId = cateId;
        }else{
          this.queryParamsProduct.cateChildId = cateId ;
        }
        listProduct(this.queryParamsProduct).then(res => {
          this.productList = res.rows;
          this.totalGoods = res.total;
        })
      },
      changeProductType(val){
        console.log('confirm', val);
        for (var index in this.productTypeOptions) {
          if (this.productTypeOptions[index].id === val) {
          }
        }
        this.getProductTypeChildList(1,val);
        this.getProductList(0,val);
      },
      changeProductTypeChild(val){
        for (var index in this.productTypeChildOptions) {
          if (this.productTypeChildOptions[index].id === val) {
            // var isTown = this.productTypeChildOptions[index].isTown;
            // console.log('isTown',isTown);
            // this.form.isTown = isTown;
          }
        }
        this.getProductList(1,val);
      },
      /**
       *  修改数量
       **/
      handleCountChange(newValue,oldValue, row){
        console.log('handleCountChange',newValue);
        console.log('handleCountChange',oldValue);
        console.log('handleCountChange',row);
        row.count = newValue;
        this.formInfo = row;
        updateInfo(this.formInfo).then(response => {
          this.msgSuccess("修改成功");
          this.getList();
        }).finally(() => {
          this.buttonLoading = false;
        });
      },
      getProductTypeChildList() {
        var that = this;
        listAll(this.queryParamsPty).then(response => {
          console.log('getProductTypeChildList', response.data);
          that.productTypeOptions = response.data;
        });
      },
      goEditInfo(){
        this.isEdit = true;
        this.resetInfo();
        this.getProductTypeChildList(0,0);
      },
      cancelEdit(){
        this.isEdit = false;
      },
      resetInfo(){
        this.formInfo = {
          id: undefined,
          orderId: this.queryParams.orderId,
          productId: undefined,
          tableId:this.order.merTableId,
          merId:this.order.merId,
          skuId: undefined,
          skuName:undefined,
          count: undefined,
          verifyCode: undefined,
          isVerify: undefined,
          singlePrice: undefined,
          originPrice: undefined,
          costPrice: undefined,
          createTime: undefined,
          state: undefined,
          totalMoney: undefined,
          activityMinsMoney: undefined,
          merRate: undefined,
          merFee: undefined,
          merSettlement: undefined,
        };
        this.resetForm("form");
      },
      handleUpdate(row){
        this.loading = true;
        this.resetInfo();
        const id = row.id || this.ids;
        getInfo(id).then(response => {
          this.loading = false;
          this.formInfo = response.data;
          this.isEdit = true;

          this.attrValues = response.data.attrValues;
          if(this.formInfo.cateId != undefined){
            this.getProductList(0,this.formInfo.cateId );
          }

          this.getProductTypeChildList(0,0);
        });
      },
      cancel(){
        this.isEdit = false;
        this.resetInfo();
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除该订单该详情内容？').then(() => {
          this.loading = true;
          return delInfo(ids);
        }).then(() => {
          this.loading = false;
          this.getList();
          this.msgSuccess("删除成功");
        }).finally(() => {
          this.loading = false;
        });
      },
      /** 提交按钮 */
        submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.buttonLoading = true;
            console.log(this.formInfo)
            if (this.formInfo.id != null) {
              updateInfo(this.formInfo).then(response => {
                this.msgSuccess("修改成功");
                this.isEdit = false;
                this.getList();
              }).finally(() => {
                this.buttonLoading = false;
              });
            } else {
              addInfo(this.formInfo).then(response => {
                this.msgSuccess("新增成功");
                this.isEdit = false;
                this.getList();
              }).finally(() => {
                this.buttonLoading = false;
              });
            }
          }
        });
      },
    }
  };
</script>
<style scoped lang="scss">

  .time {
    font-size: 13px;
    color: #999;
  }

  .bottom {
    line-height: 12px;
  }

  .button {
    padding: 0;
    float: right;
  }

  .image {
    width: 100%;
    display: block;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }

  .clearfix:after {
    clear: both
  }
  .el-card__headerbg{
    background-color: #dcdada;
  }
  .card-view-text{
    text-overflow: ellipsis;
    overflow: hidden;
    text-overflow:ellipsis;
    white-space: nowrap;
  }
</style>



